<template>
  <div class="add-exercise-container">
    <h2 class="mb-4 text-left">
      添加练习题目
    </h2>
    <!-- 班级选择框（教师可见） -->
    <div
      v-if="isTeacher"
      class="mb-3 text-left"
    >
      <label class="form-label">选择班级</label>
      <select
        v-model="selectedClassId"
        class="form-control"
        :disabled="!teacherClasses.length"
        @change="handleClassChange"
      >
        <option value="">
          请选择班级
        </option>
        <option
          v-for="cls in teacherClasses"
          :key="cls.classesId"
          :value="cls.classesId"
        >
          {{ cls.classesName }}
        </option>
      </select>
      <div
        v-if="!selectedClassId && isTeacher"
        class="text-danger mt-1"
      >
        请选择要布置练习的班级
      </div>
    </div>
    <!-- 全局错误提示 -->
    <div
      v-if="errorMessage"
      class="alert alert-danger mb-4"
    >
      {{ errorMessage }}
    </div>

    <form
      class="mb-4"
      @submit.prevent="handleSubmitExercise"
    >
      <!-- 练习基本信息 -->
      <div class="mb-3 text-left">
        <label class="form-label">练习名称</label>
        <input
          v-model="exerciseForm.exerciseName"
          type="text"
          class="form-control"
          placeholder="请输入练习名称"
        >
        <div
          v-if="!exerciseForm.exerciseName?.trim() && isExerciseTouched"
          class="text-danger mt-1"
        >
          练习名称不能为空
        </div>
      </div>

      <div class="mb-3 text-left">
        <label class="form-label">开始时间</label>
        <input
          v-model="exerciseForm.startTime"
          type="datetime-local"
          class="form-control"
        >
        <div
          v-if="!exerciseForm.startTime && isExerciseTouched"
          class="text-danger mt-1"
        >
          请选择开始时间
        </div>
      </div>

      <div class="mb-3 text-left">
        <label class="form-label">截止时间</label>
        <input
          v-model="exerciseForm.deadline"
          type="datetime-local"
          class="form-control"
        >
        <div
          v-if="!exerciseForm.deadline && isExerciseTouched"
          class="text-danger mt-1"
        >
          请选择截止时间
        </div>
        <div
          v-if="exerciseForm.startTime && exerciseForm.deadline && new Date(exerciseForm.startTime) >= new Date(exerciseForm.deadline)"
          class="text-danger mt-1"
        >
          开始时间不能晚于截止时间
        </div>
      </div>

      <div class="mb-3 text-left">
        <label class="form-label">是否允许多次提交</label>
        <select
          v-model="exerciseForm.isMultipleSubmission"
          class="form-control"
        >
          <option value="true">
            是
          </option>
          <option value="false">
            否
          </option>
        </select>
      </div>

      <!-- 添加题目区域 -->
      <div class="mb-3 text-left">
        <h4>添加题目</h4>
        
        <!-- 题目内容 -->
        <div class="mb-3 text-left">
          <label class="form-label">题目内容</label>
          <textarea
            v-model="newQuestion.questionContent"
            class="form-control"
            rows="3"
            placeholder="请输入题目内容（选择题需包含问题描述，选项在下方输入）"
            @input="isQuestionTouched = true"  
          />
          <!-- 关键修复：添加可选链?. -->
          <div
            v-if="!newQuestion.questionContent?.trim() && isQuestionTouched"
            class="text-danger mt-1"
          >
            题目内容不能为空
          </div>
        </div>

        <div class="mb-3 text-left">
          <label class="form-label">题目类型</label>
          <select
            v-model.number="newQuestion.type"
            class="form-control"
            @change="handleTypeChange"  
          >
            <option value="0">
              选择题（客观题）
            </option>
            <option value="1">
              主观题
            </option>
          </select>
        </div>

        <!-- 选择题选项 -->
        <div
          v-if="newQuestion.type === 0"
          class="mb-3 text-left"
        >
          <label class="form-label">选项（至少2个）</label>
          <div
            v-for="(opt, idx) in newQuestion.options"
            :key="idx"
            class="mb-2"
          >
            <div class="input-group">
              <span class="input-group-text">{{ getOptionLabel(idx) }}</span>
              <input
                v-model="newQuestion.options[idx]"
                type="text"
                class="form-control"
                placeholder="请输入选项内容"
                @input="isQuestionTouched = true"  
              >
              <button
                v-if="newQuestion.options.length > 2"
                type="button"
                class="btn btn-danger ms-2"
                @click="removeOption(idx)"
              >
                删除选项
              </button>
            </div>
            <!-- 关键修复：添加可选链?. -->
            <div
              v-if="!newQuestion.options[idx]?.trim() && isQuestionTouched"
              class="text-danger mt-1"
            >
              选项内容不能为空
            </div>
          </div>
          <div
            v-if="newQuestion.options.length < 2 && isQuestionTouched"
            class="text-danger mt-1"
          >
            选择题至少需要2个选项
          </div>
          <button
            type="button"
            class="btn btn-primary mt-2"
            @click="addOption"
          >
            添加选项
          </button>
        </div>

        <!-- 答案输入 -->
        <div class="mb-3 text-left">
          <label class="form-label">正确答案</label>
          <input
            v-model="newQuestion.questionAnswer"
            type="text"
            class="form-control"
            placeholder="选择题格式：A/AB；主观题输入参考答案"
            @input="isQuestionTouched = true"  
          >
          <!-- 关键修复：添加可选链?. -->
          <div
            v-if="!newQuestion.questionAnswer?.trim() && isQuestionTouched"
            class="text-danger mt-1"
          >
            答案不能为空
          </div>
        </div>

        <div class="mb-3 text-left">
          <label class="form-label">题目分数（1-100分，必须为正整数）</label>
          <input
            v-model.number="newQuestion.score"
            type="number" 
            class="form-control"
            min="1"
            max="100"
            placeholder="请输入整数分数"  
            @input="handleScoreInput"
          >
          <div
            v-if="(!newQuestion.score || newQuestion.score < 1 || newQuestion.score > 100 || !Number.isInteger(newQuestion.score)) && isQuestionTouched"
            class="text-danger mt-1"
          >
            分数必须为1-100之间的正整数
          </div>
        </div>

        <!-- 添加题目按钮 -->
        <button
          type="button"
          class="btn btn-primary"
          :disabled="!isQuestionValid"
          @click="handleAddQuestion"
        >
          添加题目
        </button>
        <div
          v-if="questionError"
          class="text-danger mt-2"
        >
          {{ questionError }}
        </div>
      </div>

      <!-- 已添加题目列表 -->
      <div class="card mt-4">
        <div class="card-header bg-primary text-white">
          已添加题目（{{ exerciseForm.questions.length }}道）
        </div>
        <ul class="list-group list-group-flush">
          <li
            v-for="(q, idx) in exerciseForm.questions"
            :key="q.questionId"
            class="list-group-item d-flex justify-content-between align-items-center"
          >
            <div>
              <h5 class="mb-1">
                {{ q.questionContent }}
              </h5>
              <p class="mb-0 text-muted">
                类型：{{ q.type ? '主观题' : '选择题' }} | 
                分数：{{ q.score }}分 | 
                答案：{{ q.questionAnswer }}
              </p>
            </div>
            <button
              type="button"
              class="btn btn-danger"
              @click="handleDeleteQuestion(idx)"
            >
              删除
            </button>
          </li>
        </ul>
      </div>

      <!-- 提交按钮 -->
      <div class="mt-4 text-left">
        <button
          type="button"
          class="btn btn-success"
          :disabled="!isExerciseValid || isSubmitting || (isTeacher && !selectedClassId)"
          @click="handleSubmitExercise"
        >
          {{ isSubmitting ? '提交中...' : `提交练习（共${exerciseForm.questions.length}道题）` }}
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    courseId: { type: String, required: true },
    userId: { type: String, required: true },
    classes: { type: Array }, // 接收父组件传递的班级列表
    userRole: { type: String, default: 'student' } // 接收用户角色
  },
  mounted() {
    console.log('AddExercise组件接收到的班级列表:', this.classes);
    // 如果有班级数据，自动选择第一个班级
    if (this.isTeacher && this.teacherClasses.length > 0 && !this.selectedClassId) {
      this.selectedClassId = this.teacherClasses[0].classesId;
      this.exerciseForm.classesId = this.selectedClassId;
      console.log('自动选择第一个班级:', this.selectedClassId);
    }
  },
  data() {
    return {
      isSubmitting: false,
      errorMessage: '',
      isExerciseTouched: false,
      isQuestionTouched: false,
      questionError: '',
      selectedClassId: '', // 选中的班级ID
      exerciseForm: {
        exerciseId: '',
        exerciseName: '',
        startTime: '',
        deadline: '',
        isMultipleSubmission: true,
        classesId: '', // 最终提交的班级ID
        exerciseScore: 0,
        questions: []
      },
      // 关键修复：初始化newQuestion所有属性为安全值
      newQuestion: {
        questionId: '',
        questionContent: '', // 初始化为空字符串
        type: 0,
        options: ['', ''], // 初始化为包含2个空字符串的数组
        questionAnswer: '', // 初始化为空字符串
        score: 10 // 初始化为有效整数
      }
    };
  },
  computed: {
    isTeacher() {
      return this.userRole === 'teacher';
    },
    teacherClasses() {
      return this.classes || [];
    },
    effectiveClassId() {
      return this.isTeacher 
        ? this.selectedClassId 
        : (this.classes?.[0]?.classesId || '');
    },
    // 新增计算属性：题目是否有效（避免直接使用!isQuestionValid导致的未定义问题）
    isQuestionValid() {
      return !this.validateQuestion();
    },
    isExerciseValid() {
      return !this.validateExercise();
    }
  },
  watch: {
    userRole(newRole) {
      if (newRole === 'student' && this.classes?.length) {
        this.selectedClassId = this.classes[0].classesId;
        this.exerciseForm.classesId = this.classes[0].classesId;
      }
    }
  },
  created() {
    if (!this.isTeacher && this.classes?.length) {
      this.exerciseForm.classesId = this.classes[0].classesId;
      this.selectedClassId = this.classes[0].classesId;
    }
  },
  methods: {
    handleClassChange() {
      // 当教师选择班级时，更新练习的班级ID
      if (this.isTeacher) {
        this.exerciseForm.classesId = this.selectedClassId;
        console.log('选中班级ID:', this.selectedClassId); // 可选：调试日志
      }
    },

    // 原有的其他方法...
    generateId(prefix = 'Q') {
      return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    },
    getOptionLabel(index) {
      return String.fromCharCode('A'.charCodeAt(0) + index);
    },
    addOption() {
      this.newQuestion.options.push('');
    },
    removeOption(index) {
      this.newQuestion.options.splice(index, 1);
    },
    handleTypeChange() {
      this.isQuestionTouched = false;
      this.questionError = '';
      if (this.newQuestion.type === 0) {
        this.newQuestion.options = ['', '']; // 重置为2个空字符串
        this.newQuestion.questionAnswer = '';
      } else {
        this.newQuestion.options = []; // 主观题无选项
      }
    },
    handleScoreInput(e) {
      const value = parseInt(e.target.value, 10);
      this.newQuestion.score = value > 0 && value <= 100 ? value : 10;
    },
    validateQuestion() {
      let error = '';
      // 关键修复：添加?.空值保护
      if (!this.newQuestion?.questionContent?.trim()) {
        error = '题目内容不能为空';
      } else if (this.newQuestion.type === 0) {
        if (this.newQuestion.options.length < 2) {
          error = '选择题至少需要2个选项';
        } else if (this.newQuestion.options.some(opt => !opt?.trim())) { // 检查每个选项是否为空
          error = '选择题选项不可为空';
        } else if (!this.newQuestion.questionAnswer?.trim()) { // 答案空值保护
          error = '请输入正确答案';
        }
      } else {
        if (!this.newQuestion.questionAnswer?.trim()) { // 主观题答案空值保护
          error = '主观题答案不能为空';
        }
      }
      // 分数验证（已确保初始化为10，无需空值保护）
      if (!Number.isInteger(this.newQuestion.score) || this.newQuestion.score < 1 || this.newQuestion.score > 100) {
        error = '分数必须为1-100之间的正整数';
      }
      return error;
    },
    handleAddQuestion() {
      this.isQuestionTouched = true;
      this.questionError = this.validateQuestion();
      if (!this.isQuestionValid) return;

      this.newQuestion.questionId = this.generateId();
      const question = {
        questionId: this.newQuestion.questionId,
        questionContent: this.newQuestion.type === 0 
          ? `${this.newQuestion.questionContent}\n${this.newQuestion.options.map((opt, idx) => `${this.getOptionLabel(idx)}. ${opt}`).join('\n')}` 
          : this.newQuestion.questionContent,
        type: this.newQuestion.type === 0 ? false : true,
        questionAnswer: this.newQuestion.questionAnswer,
        score: this.newQuestion.score,
        options: this.newQuestion.type === 0 ? this.newQuestion.options : []
      };
      
      this.exerciseForm.questions.push(question);
      this.resetQuestionForm();
    },
    resetQuestionForm() {
      // 关键修复：重置时确保所有属性为安全值
      this.newQuestion = {
        questionId: '',
        questionContent: '',
        type: 0,
        options: ['', ''],
        questionAnswer: '',
        score: 10
      };
      this.isQuestionTouched = false;
      this.questionError = '';
    },
    validateExercise() {
      const now = new Date();
      const startTime = this.exerciseForm.startTime ? new Date(this.exerciseForm.startTime) : now;
      const deadline = this.exerciseForm.deadline ? new Date(this.exerciseForm.deadline) : now;

      this.exerciseForm.isMultipleSubmission = this.exerciseForm.isMultipleSubmission === 'true';

      let error = '';
      // 关键修复：练习名称空值保护
      if (!this.exerciseForm.exerciseName?.trim()) {
        error = '练习名称不能为空';
      } else if (!this.exerciseForm.startTime) {
        error = '请选择开始时间';
      } else if (!this.exerciseForm.deadline) {
        error = '请选择截止时间';
      } else if (startTime >= deadline) {
        error = '开始时间不能晚于截止时间';
      } else if (this.exerciseForm.questions.length === 0) {
        error = '请至少添加1道题目';
      } else {
        const totalScore = this.exerciseForm.questions.reduce((sum, q) => sum + q.score, 0);
        if (totalScore === 0 || !Number.isInteger(totalScore)) {
          error = '练习总分必须为正整数';
        }
        this.exerciseForm.exerciseScore = totalScore;
      }
      return error;
    },
    async handleSubmitExercise() {
      if (this.isTeacher && !this.selectedClassId) {
        this.errorMessage = '请选择要布置练习的班级';
        return;
      }
      this.exerciseForm.classesId = this.effectiveClassId;
      this.isExerciseTouched = true;
      this.errorMessage = this.validateExercise();
      if (!this.isExerciseValid) return;

      this.isSubmitting = true;
      this.exerciseForm.exerciseId = this.generateId('EX');
      const exerciseQuestions = this.exerciseForm.questions.map(question => ({
        id: { exerciseId: this.exerciseForm.exerciseId, questionId: question.questionId }
      }));

      const requestBody = {
        exerciseName: this.exerciseForm.exerciseName,
        exerciseStartTime: this.exerciseForm.startTime,
        exerciseDeadline: this.exerciseForm.deadline,
        classesId: this.exerciseForm.classesId,
        isMultipleSubmission: this.exerciseForm.isMultipleSubmission,
        exerciseScore: this.exerciseForm.exerciseScore
      };
      
      // 移除exerciseId，让后端生成，避免ID冲突
      // 移除questions字段，因为ExerciseCreateDto中没有这个字段
      
      console.log('提交的练习数据:', JSON.stringify(requestBody, null, 2));

      try {
        // 第一步：创建练习
        const response = await axios.post('/api/exercises', requestBody);
        if (response.status === 201) {
          const createdExercise = response.data;
          console.log('练习创建成功:', createdExercise);
          
          // 第二步：如果有题目，添加到课程题库并关联到练习
          if (this.exerciseForm.questions && this.exerciseForm.questions.length > 0) {
            try {
              // 为每个题目创建关联
              const exerciseId = createdExercise.exerciseId;
              const promises = this.exerciseForm.questions.map(question => {
                return axios.post(`/api/exercises/bank/${this.courseId}/questions`, {
                  questionId: question.questionId,
                  questionContent: question.questionContent,
                  questionAnswer: question.questionAnswer,
                  type: question.type,
                  questionScore: question.score,
                  exerciseId: exerciseId // 添加练习ID以便后端关联
                });
              });
              
              await Promise.all(promises);
              console.log('题目添加到题库并关联到练习成功');
            } catch (questionError) {
              console.error('题目关联创建失败:', questionError);
              // 即使题目关联失败，练习已经创建成功
            }
          }
          
          alert('练习创建成功！');
          this.resetAllForms();
        } else {
          this.errorMessage = `创建失败：${response.data.msg || '未知错误'}`;
        }
      } catch (error) {
        this.errorMessage = `提交失败：${error.response?.data.msg || '网络错误'}`;
        console.error(error);
      } finally {
        this.isSubmitting = false;
      }
    },
    resetAllForms() {
      this.exerciseForm = {
        exerciseId: '',
        exerciseName: '',
        startTime: '',
        deadline: '',
        isMultipleSubmission: true,
        classesId: '',
        exerciseScore: 0,
        questions: []
      };
      this.resetQuestionForm();
      this.isExerciseTouched = false;
      this.errorMessage = '';
    },
    handleDeleteQuestion(index) {
      this.exerciseForm.questions.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.add-exercise-container {
  padding: 2rem;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin: 0 auto;
}

.form-label {
  font-weight: 600; 
  margin-bottom: 0.5rem;
  color: #2c3e50; 
}

textarea.form-control {
  min-height: 100px; 
  resize: vertical; 
}

.input-group {
  margin-top: 0.5rem;
}

.btn {
  margin-top: 0.5rem;
  margin-right: 0.5rem;
  padding: 0.375rem 0.75rem;
  border-radius: 4px;
}

.card {
  margin-top: 2rem;
  border: 1px solid #e0e0e0;
}

.list-group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #f0f0f0;
}

.text-danger {
  color: #e74c3c; 
  font-size: 0.875rem;
  margin-top: 0.25rem;
  font-weight: 500; 
}

button[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

.alert {
  padding: 0.75rem 1.25rem;
  margin-bottom: 1rem;
  border: 1px solid transparent;
  border-radius: 0.25rem;
}

.alert-danger {
  color: #721c24;
  background-color: #f8d7da;
  border-color: #f5c6cb;
}
</style>
